package com.system.es;

import com.alibaba.fastjson.JSONObject;
import com.component.domain.Content;
import com.component.domain.MChannel;
import com.component.service.ContentService;
import com.component.service.MNoticeService;
import com.component.service.NoteService;
import com.system.common.ContextUtils;
import com.system.common.Result;
import com.system.es.dto.Note;
import com.system.security.IsSecurity;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.indices.AnalyzeRequest;
import org.elasticsearch.client.indices.AnalyzeResponse;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@IsSecurity(isSecurity = false)
@RestController
@RequestMapping("es")
public class EsApi {

    @Autowired
    private EsServer esServer;

    @Autowired
    private NoteService noteService;

    @Autowired
    private ContentService contentService;

    @Autowired
    private NoteEsServer noteEsServer;

    @GetMapping("search_")
    public JSONObject search(@RequestParam(value = "pageNum",defaultValue = "1")Integer pageNum,
                             @RequestParam(value = "pageSize",defaultValue = "10")Integer pageSize,
                             @RequestParam("keyword")String keyword) throws IOException {
        Map<String,Object> map=noteEsServer.page(keyword,pageNum,pageSize);
        return Result.successInfo(map);
    }

    /**
     * 获取分词
     * @return
     */
    @GetMapping("getAnalyze")
    public JSONObject getAnalyze(@RequestParam("text")String text) throws IOException {
        List<String> strings=new ArrayList<>();
        AnalyzeRequest analyzeRequest = AnalyzeRequest.withGlobalAnalyzer("ik_smart", text);
        AnalyzeResponse analyze =esServer.getRestHighLevelClient().indices().analyze(analyzeRequest, RequestOptions.DEFAULT);
        for (AnalyzeResponse.AnalyzeToken token : analyze.getTokens()) {
            System.out.println(token.getTerm());
            strings.add(token.getTerm());
        }
        return Result.successInfo(strings);
    }

    @GetMapping("hights")
    public JSONObject hights(@RequestParam("search")String search) throws IOException {
        Map<String,Object> map= esServer.highLights("note_data",search);
        List<String> strings=new ArrayList<>();
        AnalyzeRequest analyzeRequest = AnalyzeRequest.withGlobalAnalyzer("ik_smart", search);
        AnalyzeResponse analyze =esServer.getRestHighLevelClient().indices().analyze(analyzeRequest, RequestOptions.DEFAULT);
        for (AnalyzeResponse.AnalyzeToken token : analyze.getTokens()) {
            strings.add(token.getTerm());
        }
        map.put("ik_smart",strings);
        return Result.successInfo(map);
    }

    /**
     * GET http://192.168.117.129:9200/_cat/indices
     * 获取所有索引
     * @throws IOException
     */
    @GetMapping("/getallIndexs")
    public JSONObject getAllIndexs() throws IOException {
        List<String> indexs=esServer.getAllIndexs();
        return Result.successInfo(indexs);
    }


    @GetMapping("page")
    public JSONObject page(@RequestParam(value = "pageNum",defaultValue = "1")Integer pageNum,
                           @RequestParam(value = "pageSize",defaultValue = "10")Integer pageSize,
                           @RequestParam("indexName")String indexName) throws IOException {
        Map<String,Object> maps=esServer.pageSearch(indexName,pageNum,pageSize);
        return Result.successInfo(maps);
    }

    /**
     * 高亮分页查询
     * @param pageNum  页码
     * @param pageSize 条数
     * @param search  搜索内容
     * @return
     * @throws IOException
     */
    @GetMapping("pageHighLight")
    public JSONObject pageHighlight(@RequestParam(value = "pageNum",defaultValue = "1")Integer pageNum,
                                    @RequestParam(value = "pageSize",defaultValue = "10")Integer pageSize,
                                    @RequestParam(value = "search")String search) throws IOException {
        Map<String,Object> maps=noteEsServer.pageHightLightFuzzSearch(search,pageNum,pageSize);
        return Result.successInfo(maps);
    }

    @GetMapping("/createIndex")
    public JSONObject createIndex(@RequestParam("indexName")String indexName) throws IOException {
        boolean falg=esServer.exitIndex(indexName);
        if(!falg){
            esServer.createIndex(indexName);
            return Result.successInfo("索引创建成功");
        }
        return Result.errorInfo("索引已存在");
    }

    @GetMapping("get")
    public JSONObject getDocument(@RequestParam("id")String id,
                                  @RequestParam("indexName")String indexName) throws IOException {
        Map<String,Object> objectMap=esServer.getDocumentById(indexName,id);
        return Result.successInfo(objectMap);
    }

    @GetMapping("search")
    public JSONObject search(@RequestParam("indexName")String indexName,
                             @RequestParam("field")String field,
                             @RequestParam("search")String str) throws IOException {
        List<Map<String, Object>> mapList=esServer.searchFuzzines(indexName,field,str);
        return Result.successInfo(mapList);
    }

    @GetMapping("flush")
    public JSONObject flushData() throws IOException {
        noteEsServer.loadData();
        return Result.successInfo("加载成功");
    }

    @PostMapping("add")
    public JSONObject addDocument(@RequestParam("indexName")String indexName,
                                  @RequestParam("id")Serializable id) throws Exception {
        Note note=new Note();
        com.component.domain.Note note1=noteService.getById(id);
        Content content=contentService.getContentByNid(note1.getId());
        if(content.getIsencrypt()){
            String contStr= ContextUtils.decryptStr(content.getContent());
            content.setContent(contStr);
            note.setContent(contStr);
        }
        if(note1.getmChannel()!=null){
            MChannel mChannel=note1.getmChannel();
            note.setChannelId(mChannel.getId().toString());
            note.setChannelName(mChannel.getChannelname());
        }
        BeanUtils.copyProperties(note1,note);
        Map<String,Object> data=esServer.getDocumentById(indexName,id.toString());
        if(data==null){
            esServer.addDocument(note,indexName);
        }else {
            esServer.updateDocumentById(note,indexName);
        }
        return Result.successInfo("添加成功");
    }

    /**
     * 获取所有数据
     * @param indexName
     * @return
     * @throws IOException
     */
    @GetMapping("getAll")
    public JSONObject getAllDocuments(@RequestParam("indexName")String indexName) throws IOException {
        List<Map<String,Object>> mapList=esServer.getAllDocuments(indexName);
        return Result.successInfo(mapList);
    }
}
